/* 
 * File:   llist.c
 * Author: rslmanu
 *
 * Created on 17 mai 2009, 14:01
 */

/*
Copyright (C) 2009 Roussel Emmanuel

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

//Linked list manipulation

#include <stdlib.h>
#include <stdio.h>
#include "llist.h"


//return the nb of items in the list
int ll_length(bout *p){
	int n=0;
	while(p){
		n++;
		p = p->suiv;
	}
	return n;
}

//display the content of the list in the screen.
void ll_view(bout *p){
	while(p){
		printf("x=%d, y=%d\n", p->x, p->y);
		p = p->suiv;
	}
}


//put an element in the list (at the beginning)
int ll_push(bout **p, int x, int y){
	bout *elt = malloc(sizeof(bout));
	if(!elt) return -1;     // if malloc failed
	elt->x = x;
	elt->y = y;
	elt->suiv = *p;
	*p = elt;       //pointer to the last item
	return 1;
}

//put an element in the list (at the end)
int ll_push_end(bout **p, int x, int y){
	bout *elt = malloc(sizeof(bout));
	bout *tmp_prev = NULL;
	bout *tmp=*p;

	if(!elt) return -1;     // if malloc failed
	elt->x = x;
	elt->y = y;
	elt->suiv = NULL;

	if(!tmp){
		*p=elt;
		return 1; //the list was empty, we're done.
	}

	while(tmp){
		*p = tmp;
		tmp = tmp->suiv;
	}

	(*p)->suiv = elt;
	return 1;
}


//remove one item of the list (at the beginning)
int ll_pop(bout **p){
	bout *tmp;
	if(!*p) return -1;     //return -1 if llist is empty
	tmp = (*p)->suiv;
	free(*p);
	*p = tmp;       //pointer to the last item
	return 1;
}

//remove one item of the list (at the end)
int ll_pop_end(bout **p){
	bout *tmp = *p;
	bout *tmp_prev = NULL;

	if(!*p) return -1;     //return -1 if llist is empty
	if((*p)->suiv == NULL){
		free(*p);
		*p = NULL;
		return -1;
	}

	while(tmp->suiv){
		tmp_prev = tmp;
		tmp = tmp->suiv;
	}
	tmp_prev->suiv = NULL;
	free(tmp);

	return 1;
}

bout *ll_return_last(bout *p){  //return the last item in the list
    if(!p) return NULL;     //return NULL if llist is empty
    while(p->suiv) p = p->suiv;

    return p;
}

int ll_exist(bout *p, int x, int y){
    while(p){
        if(p->x == x && p->y == y)
            return 1;
	p = p->suiv;
    }
    return 0;
}


//empty the list.
void ll_clear(bout **p){
	bout *tmp;
	while(*p){
		tmp = (*p)->suiv;
		free(*p);
		*p = tmp;
	}
}



